package org.cqepc.project.reform.controller;

import com.alibaba.fastjson2.util.DateUtils;
import org.cqepc.project.reform.model.entity.SubjectEntity;
import org.cqepc.project.reform.service.SubjectService;
import org.cqepc.project.reform.utils.result.Result;
import org.cqepc.project.reform.utils.util.SerialNoGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/subject")
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    @ResponseBody
    @GetMapping("/get_subject")
    public Result getSubject() {
        List<SubjectEntity> allSubjects = subjectService.getAllSubjects();

        return Result.ok(allSubjects);
    }

    @ResponseBody
    @PostMapping("/add_subject")
    public Result addSubject(@RequestBody SubjectEntity subject) {
        // 获取当前ID
        String maxRoundCode = subjectService.getMaxRoundCode();

        String code = "SUBJ-" + DateUtils.format(new Date(), "yyyyMMdd");
        String newCode = null;
        if (StringUtils.hasLength(maxRoundCode)) {
            // 有长度则不为空
            String getMaxCode = maxRoundCode.substring(13, 15);
            try {
                newCode = code + SerialNoGenerateUtil.getSerialNo(getMaxCode);
            } catch (Exception e) {
                return Result.fail("轮次编号已达上限");
            }
        } else {
            newCode = code + "01";
        }
        subject.setSubjectId(newCode);

        //设置创建和更新时间
        subject.setCreateTime(new Date());
        subject.setUpdateTime(new Date());

        Integer i = subjectService.insertSubject(subject);

        if (i > 0) {
            SubjectEntity subjectById = subjectService.getSubjectById(newCode);
            return Result.ok(subjectById);
        } else {
            return Result.fail("插入用户失败");
        }

    }

    @ResponseBody
    @GetMapping("/delete_subject")
    public Result deleteSubject(@RequestBody SubjectEntity subject) {
        Integer i = subjectService.deleteSubject(subject);

        if (i > 0) {
            return Result.ok("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    @ResponseBody
    @PostMapping("/update_subject")
    public Result updateSubject(@RequestBody SubjectEntity subject) {
        Integer i = subjectService.updateSubject(subject);
        if (i > 0) {
            SubjectEntity subjectById = subjectService.getSubjectById(subject.getSubjectId());
            return Result.ok(subjectById);
        } else {
            return Result.fail("更新失败");
        }
    }

}
